package com.cliff.babyshop.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Created by cliff on 2017/8/19.
 */
@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeinxinController {

    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code) {
        log.info(" 进入auth方法。。。 code={}", code);
        //081ECSjQ0mdbKb29WumQ0yV9kQ0ECSj6
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx22402411de789518&secret=a6af9a5c3f0e842e3f151c8c87138b9d&code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        log.info("返回结果{}", result);
        Gson gson = new Gson();

        Type type = new TypeToken<Map<String, Object>>() {}.getType();
        Map<String, Object> map2 = gson.fromJson(result, type);


        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + map2.get("access_token")
                + "&openid=" + map2.get("openid") + "&lang=zh_CN";
        result = restTemplate.getForObject(url, String.class);
        log.info("用戶信息={}", result);
    }
}
